package mspbots.cw.data.core.sheets;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.cw.common.ResultMsg;
import mspbots.cw.data.core.AbstractToolsUtil;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * @author Jay.Yang
 */

@Log4j2
@Component
@RequiredArgsConstructor
public class TimeSheetsReceiver extends AbstractToolsUtil {

    private final TimeSheetsRepository timeSheetsRepository;

    @RabbitListener(queues = "connect-wise.time-sheets.sync")
    public void processMessage(ResultMsg resultMsg) {

        TimeSheets data = TimeSheets.builder()
                .otherId(resultMsg.getId())
                .tenantId(resultMsg.getTenantId())
                .syncTime(resultMsg.getSyncDate())
                .extend(resultMsg.getEntity())
                .build();

        data.setUpdateTime(super.getUpdateTime(resultMsg.getEntity()));
        data.setCreateTime(super.getCreateTime(resultMsg.getEntity()));
        this.timeSheetsRepository.findByOtherIdAndTenantId(resultMsg.getId(), resultMsg.getTenantId())
                .switchIfEmpty(this.timeSheetsRepository.save(data))
                .filter(old -> old.getUpdateTime().isBefore(data.getUpdateTime()))
                .map(result -> {
                    data.setId(result.getId());
                    return data;
                })
                .flatMap(this.timeSheetsRepository::save).block(Duration.ofSeconds(10));
    }
}
